package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 专门处理feign远程调用丢失请求头的问题
 */
@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        RequestInterceptor interceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {   //feign构造的新的请求就是template
                //RequestContextHolder是spring帮助我们的获取到整个MVC线程下刚进来的请求头参数
                //其实就是:
                /*
                @GetMapping("/toTrade")
                public String toTrade(HttpServletRequest request){}
                中的HttpServletRequest request
                 */
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();  //request就是订单服务的老请求

                //既然已经拿到了请求头信息，我们就需要同步请求头数据，主要是拿到cookie信息
                //因为我们想在订单服务下面调用购物车服务，拿到登陆的用户的信息，如果丢失了cookie，就拿了个寂寞
                String cookie = request.getHeader("Cookie"); //获取到老请求的所有cookie
                template.header("Cookie",cookie);   //将老请求的所有cookie同步到新请求的cookie

            }
        };
        return interceptor;
    }
}
